// 更新dataTable数据源
let updateTable = function () {
  let table = [];
  for (let key in this.unitData.data) {
    table.push(this.unitData.data[key]);
  }
  this.unitData.table = Object.assign([], table);
};

// 更新数据源索引
let updateIndex = function () {
  let index = {};
  for (let key in this.unitData.data) {
    let data = this.unitData.data[key];
    index[data.name] = data.id;
  }
  this.unitData.index = Object.assign({}, index);
};


export default {
  isLogin(state, payload) {
    state.isLogin = payload;
  },
  saveServerInfo(state, payload) {
    state.serverInfo = payload || null;
  },
  saveUserInfo(state, payload) {
    state.userInfo = payload || null;
  },
  setUnitData(state, payload) {
    state.unitData.data = Object.assign(state.unitData.data, (payload || {}));

    // 同步索引和表格数据源
    updateTable.call(state);
    updateIndex.call(state);
  },
  delUnitData(state, payload) {
    if (payload && typeof payload.id !== 'undefined') {
      delete state.unitData.data[payload.id];

      // 同步索引和表格数据源
      updateTable.call(state);
      updateIndex.call(state);
    }
  },
}
